import Koa from 'koa'
import KoaSession from 'koa-session'
import KoaCookies from 'koa-cookie'
import resource from 'koa-static'
import cors from 'koa2-cors'
import routes from './routes'
import bodyParser from 'koa-bodyparser'
import xmlBodyParse from 'koa-xml-body'

process.env.TZ = 'Asia/Shanghai'


const CONFIG = {
    key: 'koa:sess', /** 默认 */
    maxAge: 10000,  /*  cookie的过期时间        【需要修改】  */
    overwrite: true, /** (boolean) can overwrite or not (default true)    没有效果，默认 */
    httpOnly: true, /**  true表示只有服务器端可以获取cookie */
    signed: true, /** 默认 签名 */
    rolling: true, /** 在每次请求时强行设置 cookie，这将重置 cookie 过期时间（默认：false） 【需要修改】 */
    renew: false, /** (boolean) renew session when session is nearly expired      【需要修改】*/
};

const app = new Koa()
app.keys = ['asdfsdfsdfs-asdfas-df-asdg-sdfgsd'];
app.use(cors())
app.use(resource(__dirname+ '/../view',{ extensions: ['jpg','png','txt','html','js','.css','.json']}))
app.use(xmlBodyParse({xmlOptions: {explicitArray: false}}))
app.use(bodyParser())
app.use(KoaCookies())
app.use(KoaSession(CONFIG, app))
app.use(async(ctx, next)=>{
    try {
        let data = await next()
        ctx.body = { success : true, data : data }
    } catch (error) {
        console.log(error)
        ctx.body = { success : false, message : error  }
    }
})
app.use(routes.routes()).use(routes.allowedMethods())
app.listen(process.env.PORT || 9000, '0.0.0.0')